﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Collections.ObjectModel;
using IndexMarkSilverlightClient.Views;
using IndexMarkSilverlightClient.IndexMarkServiceReference;
using System.Windows.Data;
using IndexMarkSilverlightClient.Classes;
using System.ComponentModel;
using IndexMarkSilverlightClient;
using System.Threading;
using System.Windows.Media;
using SharedCode.Controls;
using System.Collections.Generic;
using IndexMarkSilverlightClient.Classes.Converters;
using SharedCode;

namespace IndexMarkSilverlightClient
{
    public partial class InputMain : Page
    {
        InputMainViewModel viewModel = null;
        RespondentAnswers CurrentRA = null;
        bool CathedraFilterEmpty = true;

        public InputMain()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(InputMain_Loaded);
            viewModel = Resources["InputMainViewModel"] as InputMainViewModel;
            viewModel.LoadCompleted += new ViewModelBase.LoadEventHandler(viewModel_LoadCompleted);
            viewModel.LoadError += new ViewModelBase.ErrorEventHandler(viewModel_LoadError);
        }

        void viewModel_LoadError(object sender, ErrorEventArgs e)
        {
            loadingBar.Collapse();
            SetOpacityControls(1, true);
        }

        void viewModel_LoadCompleted(object sender, LoadEventArgs e)
        {
            if (e.Type == typeof(RespondentAnswers))
            {
                if (CurrentRA != null)
                {
                    IndexMarkView.UpdateLayout();
                    this.IndexMarkView.ScrollIntoView(this.CurrentRA, null);
                    this.CurrentRA = null;
                }
                CathedraFilterEmpty = true;
                AnswersFilterCB.SelectedIndex = 0;
                SetWidthColumns();
            }
            SetOpacityControls(1, true);
            loadingBar.Collapse();
        }

        void InputMain_Loaded(object sender, RoutedEventArgs e)
        {
            //var vm = ((((this.Parent as Frame).Parent as Border).Parent as Grid).Parent as MainPage).ViewModel;
            var vm = MainPage.ViewModel;
            vm.UserLoaded += new EventHandler(ViewModel_UserLoaded);

            //отписываемся
            vm.SelectTerm -= ViewModel_SelectTerm;
            //подписываемся
            vm.SelectTerm += new MainViewModel.SelectTermEventHandler(ViewModel_SelectTerm);
            //чтобы не вылетало ошибки на 1 разе

            //if(vm.CurrentTerm == null){ vm.CurrentTerm = ;
            //    viewModel.LoadTerms();
            //}

            Term CurTerm = vm.CurrentTerm;
            //загружаем юзера
            viewModel.User = vm.User;

            if (CurTerm != null)
            {
                vm.SelectTermInit();
            }

            loadingBar.Show();
            SetOpacityControls(0, false);

            //CatherdaFilter.ItemFilter = (search, item) =>
            //{
            //    Department dep = item as Department;
            //    if (dep != null)
            //    {
            //        string filter = search.ToString();
            //        return dep.Name.ToLower().Contains(filter.ToLower());
            //    }
            //    return false;
            //};

            //устанавливаем режим "отображать все показатели"
            AllVisibleCB.SelectedIndex = 0;
        }

        void ViewModel_UserLoaded(object sender, EventArgs e)
        {
            var vm = MainPage.ViewModel;
            viewModel.User = vm.User;
            //MessageBox.Show(vm.CurrentTerm.IDOrganization.ToString());
        }

        void ViewModel_SelectTerm(object sender, SelectTermEventsArgs e)
        {
            SetOpacityControls(0, false);
            loadingBar.Show();
            viewModel.CurrentTerm = e.SelectTerm;
            viewModel.User = e.User;
            //MessageBox.Show(viewModel.User.Permissions.First().Char.Name);
        }

        void SetWidthColumns()
        {
            IndexMarkView.Width = DataGridColumn.ActualWidth;

            //ФИО
            IndexMarkView.SetSizeColumn(IndexMarkView.Columns[0], new SizeColumn
            {
                ColumnWidth = 15,
                DataGridWidth = IndexMarkView.Width
            });

            //должность
            IndexMarkView.SetSizeColumn(IndexMarkView.Columns[1], new SizeColumn
            {
                ColumnWidth = 24,
                DataGridWidth = IndexMarkView.Width
            });

            //показатели
            IndexMarkView.SetSizeColumn(IndexMarkView.Columns[2], new SizeColumn
            {
                ColumnWidth = 52.9,
                DataGridWidth = IndexMarkView.Width
            });

            //редактирование
            IndexMarkView.SetSizeColumn(IndexMarkView.Columns[3], new SizeColumn
            {
                ColumnWidth = 8,
                DataGridWidth = IndexMarkView.Width
            });
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);
        }


        private void IndexMarkTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            IndexMarkItem item = (sender as TreeView).SelectedItem as IndexMarkItem;

            #region установка цвета выделенного элемента. Сначала все элементы сбрасываем, затем у выделенного устанавливаем нужный фон
            List<TreeViewItem> items = (sender as TreeView).AllItems().ToList();
            foreach (TreeViewItem child in items)
            {
                if (child != null)
                    child.Background = new SolidColorBrush(Colors.Transparent);
            }
            TreeViewItem SelectedItem = (sender as TreeView).ContainerFromItem(item);
            if (SelectedItem != null)
            {
                LinearGradientBrush myBrush = new LinearGradientBrush();
                myBrush.GradientStops.Add(new GradientStop
                {
                    Color = Color.FromArgb(255, 63, 218, 226),
                    Offset = 0.0
                });
                myBrush.GradientStops.Add(new GradientStop
                {
                    Color = Color.FromArgb(255, 43, 198, 206),
                    Offset = 0.5
                });
                myBrush.GradientStops.Add(new GradientStop
                {
                    Color = Color.FromArgb(255, 36, 168, 174),
                    Offset = 1.0
                });
                SelectedItem.Background = myBrush;
            }
            #endregion

            if (item is Characteristic)
            {
                SetOpacityControls(0.6, false);
                loadingBar.Show();

                viewModel.CurrentChar = item as Characteristic;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Respondent CurrentResp = (IndexMarkView.SelectedItem as RespondentAnswers).Resp;
            RespAnswersWindow win = new RespAnswersWindow();
            win.Title = CurrentResp.ShortName + " - " + CurrentResp.Position + " " + CurrentResp.Status + "ст.";

            win.ViewModel.CurrentChar = viewModel.CurrentChar;
            win.ViewModel.CurrentTerm = viewModel.CurrentTerm;
            win.ViewModel.RespAnswers.Resp = (IndexMarkView.SelectedItem as RespondentAnswers).Resp;

            this.CurrentRA = IndexMarkView.SelectedItem as RespondentAnswers;

            win.Show();
            win.Closing += new EventHandler<CancelEventArgs>(win_Closing);
        }

        void win_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //если нажали кнопку ОК, то перезагружаем показатели
            if ((sender as RespAnswersWindow).DialogResult == true)
            {
                loadingBar.Show();
                SetOpacityControls(0.6, false);

                viewModel.LoadAnswers();
            }
            SetWidthColumns();
            this.IndexMarkView.ScrollIntoView(this.CurrentRA, IndexMarkView.Columns[0]);
        }

        private void IndexMarkView_LoadingRowGroup(object sender, DataGridRowGroupHeaderEventArgs e)
        {
            //скрываем имя группируемого свойства
            e.RowGroupHeader.PropertyNameVisibility = Visibility.Collapsed;
        }

        /// <summary>
        /// Метод устанавливает прозрачность элементов управления
        /// </summary>
        /// <param name="O">
        /// Прозрачность. Может быть от 0 до 255. 0 - элемент невидим, 255 - элемент видим
        /// </param>
        private void SetOpacityControls(double O, bool Enabled)
        {
            foreach (UIElement ctrl in this.LayoutRoot.Children)
            {
                ctrl.Opacity = O;
            }
            IndexMarkTreeView.IsEnabled = Enabled;
            IndexMarkView.IsEnabled = Enabled;
            //CatherdaFilter.IsEnabled = Enabled;
            DepFilter.IsEnabled = Enabled;
            loadingBar.Opacity = 1;
        }

        private void CatherdaFilter_DropDownClosing(object sender, RoutedPropertyChangingEventArgs<bool> e)
        {
            viewModel.CurrentDep = (sender as AutoCompleteBox).SelectedItem as Department;

            if ((viewModel.CurrentChar != null)
                //&& (viewModel.CurrentDep.ToString() == (sender as AutoCompleteBox).SearchText)
                )
            {
                SetOpacityControls(0.6, false);
                loadingBar.Show();
                viewModel.LoadAnswers();
                AnswersFilterCB.SelectedIndex = 0;
            }
        }

        private void RespFilter_TextChanged(object sender, TextChangedEventArgs e)
        {
            FilteringAnswers(RespFilter.Text, SelectAnswersFilterType());
        }

        private void CatherdaFilter_TextChanged(object sender, RoutedEventArgs e)
        {
            CathedraFilterEmpty = false;
        }

        private void ChildTable_Loaded(object sender, RoutedEventArgs e)
        {
            (sender as xDataGrid).Width = IndexMarkView.Columns[2].ActualWidth;
            //Градация
            (sender as xDataGrid).SetSizeColumn((sender as xDataGrid).Columns[0], new SizeColumn
            {
                ColumnWidth = 70,
                DataGridWidth = (sender as xDataGrid).Width
            });

            //Объем
            (sender as xDataGrid).SetSizeColumn((sender as xDataGrid).Columns[1], new SizeColumn
            {
                ColumnWidth = 29.9,
                DataGridWidth = (sender as xDataGrid).Width
            });

        }

        private void CatherdaFilter_LostFocus(object sender, RoutedEventArgs e)
        {
            //когда фильтр очищается, необходимо загрузить ВСЕ показатели
            //if (CatherdaFilter.Text == String.Empty && CathedraFilterEmpty == false)
            //{
            //    if (viewModel.CurrentChar != null)
            //    {
            //        SetOpacityControls(0.6, false);
            //        loadingBar.Show();

            //        viewModel.CurrentDep = null;
            //        viewModel.LoadAnswers();

            //        CatherdaFilter.Text = "";
            //        CathedraFilterEmpty = true;
            //        SetWidthColumns();
            //    }
            //}
        }

        private void RespFilter_LostFocus(object sender, RoutedEventArgs e)
        {
            SetWidthColumns();
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            viewModel.AllVisible = (sender as ComboBox).SelectedIndex == 0;
        }

        private void TextBlock_Loaded(object sender, RoutedEventArgs e)
        {
            //делаем привязку к свойству Volume
            Binding binding = new Binding("Text");
            binding.Converter = new AnswerToVolumeConverter();
            binding.Path = new PropertyPath("Volume");
            binding.ConverterParameter = viewModel.CurrentChar;
            (sender as TextBlock).SetBinding(TextBlock.TextProperty, binding);
        }

        private void GridSplitter_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            SetWidthColumns();
        }

        private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (IndexMarkView != null)
            {
                FilteringAnswers(RespFilter.Text, SelectAnswersFilterType());
            }

        }

        private AnswersFilterType SelectAnswersFilterType()
        {
            if (AnswersFilterCB.SelectedIndex == 0)
            {
                return AnswersFilterType.All;
            }
            if (AnswersFilterCB.SelectedIndex == 1)
            {
                return AnswersFilterType.NotEmpty;
            }
            if (AnswersFilterCB.SelectedIndex == 2)
            {
                return AnswersFilterType.Empty;
            }
            return AnswersFilterType.All;
        }

        private void FilteringAnswers(String FIO, AnswersFilterType Type)
        {
            (IndexMarkView.ItemsSource as PagedCollectionView).Filter = (obj) =>
            {
                var ra = (RespondentAnswers)obj;
                var r = ra.Resp;

                bool Filter1 = false;
                switch (Type)
                {
                    case AnswersFilterType.All: Filter1 = true; break;
                    case AnswersFilterType.NotEmpty: Filter1 = ra.Answers.Count > 0; break;
                    case AnswersFilterType.Empty: Filter1 = ra.Answers.Count == 0; break;
                }

                bool Filter2 = false;
                Filter2 = String.IsNullOrEmpty(FIO) || r.FullName.ToLower().Contains(FIO.ToLower());

                return Filter1 && Filter2;// && r.Status;// && R;
            };
        }

        private void CatherdaFilter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            viewModel.CurrentDep = (sender as ComboBox).SelectedItem as Department;

            if ((viewModel.CurrentChar != null) && (viewModel.CurrentDep == (sender as ComboBox).SelectedItem))
            {
                SetOpacityControls(0.6, false);
                loadingBar.Show();
                viewModel.LoadAnswers();
                AnswersFilterCB.SelectedIndex = 0;
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            viewModel.CurrentDep = null;
            DepFilter.SelectedIndex = -1;

            if (viewModel.CurrentChar != null)
            {
                SetOpacityControls(0.6, false);
                loadingBar.Show();
                viewModel.LoadAnswers();
                AnswersFilterCB.SelectedIndex = 0;
            }
        }
    }
}